// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import router from './router'

import axios from 'axios'
import VueAxios from 'vue-axios'
import elementui from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
import VueAnimateNumber from 'vue-animate-number'
import VideoPlayer from 'vue-video-player'
import 'vue-video-player/src/custom-theme.css'
import 'video.js/dist/video-js.css'

Vue.use(VideoPlayer)
Vue.use(VueAnimateNumber)
Vue.config.productionTip = false;
Vue.use(elementui);
Vue.use(VueAxios, axios);


// axios 配置
axios.defaults.timeout = 10000;
axios.defaults.baseURL = 'http://localhost:'; 

// http request 拦截器
axios.interceptors.request.use(
  config => {
    if (localStorage.token) { //判断token是否存在
      config.headers.Authorization = localStorage.token;  //将token设置成请求头
    }
    return config;
  },
  err => {
      alert("该token已失效或者不存在！")
    return Promise.reject(err);
  }
);

// http response 拦截器
axios.interceptors.response.use(
  response => {
      // 如果token已经过期，则进行刷新token的请求
  if (response.data.code === 401) {
    // 刷新token请求
    return axios.post('/user/refreshToken', {
      token: localStorage.getItem('token')
    }).then((res) => {
      // 更新localStorage中的token信息
      localStorage.setItem('token', res.data.token);
      // 使用新的token重新发送请求
      response.config.headers.Authorization = `Bearer ${res.data.token}`;
      return axios(response.config);
    }).catch((err) => {
      // 刷新token失败，跳转到首页
      location.href = '/bindex';
    });
  }
    return response;
  },
  error => {
    return Promise.reject(error);
  }
);

//前置路由守卫 to:到某个路由 from 从哪个路由出来 next() 放行到指定的路由
router.beforeEach((to,from,next)=>{
  //获取跳转的路径
  var path = to.path;
  //判断是否为登录路由路径
  if(path==="/bindex"){
    //放行
    return next();
  }
  if(path==="/register" || path==="/findpwd"){
    //放行
    return next();
  }
 
  //其他路由路径 判断是否登录过
  var token = localStorage.getItem('token');
 
  if(token){

    return next();
  }
  //跳转登录
  alert("请先登录,在进行其他操作呦~")
 
  return next("/bindex");
})




/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,
  elementui,
  components: { App },
  template: '<App/>'
})
